package NextClass.Native;

import com.sun.net.httpserver.HttpExchange;
import vm.runtime.NextVMRuntime;

import javax.management.openmbean.InvalidOpenTypeException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import static NextClass.Native.HttpRun.getBodyAsByteArray;
import static NextClass.Native.HttpRun.getHeadersAsString;

public class Requests implements Serializable {
    public static String[] ClassMethods = {
            "run",
            "send_body",
            "message",
            "send_head",
            "code"
    };

    public static byte[] getBodyAsByteArray(HttpURLConnection httpURLConnection) throws IOException {
        InputStream is = httpURLConnection.getInputStream();
        ReadableByteChannel channel = Channels.newChannel(is);
        ByteBuffer buffer = ByteBuffer.allocate(1024); // 可以调整缓冲区大小
        int bytesRead;
        int totalBytesRead = 0;

        // 循环读取直到没有更多数据
        while ((bytesRead = channel.read(buffer)) != -1) {
            totalBytesRead += bytesRead;
            buffer.clear(); // 清除缓冲区，准备下一次读取
        }
        return buffer.array();
    }

    public static Object run(String Invoke, Object object,NextVMRuntime nextVMRuntime, Object... objects) throws Exception{
        HttpURLConnection httpURLConnection = (HttpURLConnection) object;
        if (Invoke.equals("run")) {
            httpURLConnection.connect();
            return null;
        }
        else if (Invoke.equals("send_body")) {
            byte[] bytes = (byte[]) objects[0];
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            return null;
        }
        else if (Invoke.equals("message")) {
            return getBodyAsByteArray(httpURLConnection);
        }
        else if (Invoke.equals("send_head")) {
            httpURLConnection.setRequestProperty((String) objects[0], (String) objects[1]);
            return null;
        }
        else if (Invoke.equals("code")) {
            return httpURLConnection.getResponseCode();
        }
        else {
            return null;
        }
    }
}
